package com.liuchuanzheng.lcz_wanandroid.module.detail.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.ConsoleMessage
import android.webkit.WebResourceRequest
import android.webkit.WebView
import androidx.core.app.ShareCompat
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BusUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.liuchuanzheng.lcz_wanandroid.R
import com.liuchuanzheng.lcz_wanandroid.base.BaseVMActivity
import com.liuchuanzheng.lcz_wanandroid.base.Constant
import com.liuchuanzheng.lcz_wanandroid.databinding.ActivityDetailWebBinding
import com.liuchuanzheng.lcz_wanandroid.databinding.ActivityMainBinding
import com.liuchuanzheng.lcz_wanandroid.ext.copyTextIntoClipboard
import com.liuchuanzheng.lcz_wanandroid.ext.htmlToSpanned
import com.liuchuanzheng.lcz_wanandroid.ext.showToast
import com.liuchuanzheng.lcz_wanandroid.module.common.bus.CollectStatusEvent
import com.liuchuanzheng.lcz_wanandroid.module.detail.pop.BottomToolPop
import com.liuchuanzheng.lcz_wanandroid.module.detail.viewmodel.DetailViewModel
import com.liuchuanzheng.lcz_wanandroid.module.detail.whiteHostList
import com.liuchuanzheng.lcz_wanandroid.module.home.bean.Article
import com.liuchuanzheng.lcz_wanandroid.module.user.UserManager
import com.liuchuanzheng.lcz_wanandroid.module.user.activity.LoginActivity
import com.lxj.xpopup.XPopup

/**
 * @author 刘传政
 * @date 2021/9/16 0016 14:43
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
class DetailWebActivity : BaseVMActivity<DetailViewModel>() {
    companion object {
        const val PARAM_ARTICLE = "param_article"
        fun start(context: Context, article: Article) {
            Intent(context, DetailWebActivity::class.java).run {
                putExtra(PARAM_ARTICLE, article)
                context.startActivity(this)
            }
        }
    }

    private lateinit var article: Article
    lateinit var mViewBinding: ActivityDetailWebBinding
    private var agentWeb: AgentWeb? = null


    /**
     * 因为系统自带的设置view方法有很多种,id,view都可以.所以这里不像
     * 大家都用id的封装方式,那是限制了自己
     * 建议用viewBinding的方式。个人不喜欢dataBinding
     */
    override fun setContentView() {
        mViewBinding = ActivityDetailWebBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        article = intent?.getParcelableExtra(PARAM_ARTICLE) ?: return
        mViewBinding.tvTitle.text = article.title.htmlToSpanned()
        mViewBinding.ivBack.setOnClickListener {
            finish()
        }
        mViewBinding.ivMore.setOnClickListener {
            showPop()
        }
        if (article.id != 0L) {
            mViewModel.addReadHistory(article)
        }
        initWeb()
        LiveEventBus
            .get(CollectStatusEvent::class.java)
            .observe(this, Observer { event->
                if (article.id == event.id){
                    if (article.collect != event.collect) {
                        article.collect = event.collect
                    }
                }

            })
    }

    private fun showPop() {
        var pop = XPopup.Builder(this)
            .asCustom(BottomToolPop(this, object : BottomToolPop.ResultListener {
                override fun onCkecked(maction: BottomToolPop.ClickType) {
                    when (maction) {
                        BottomToolPop.ClickType.COLLECT -> {
                            if (!UserManager.isLogin()) {
                                LoginActivity.start(activity)
                            }else{
                                changeCollect()
                            }
                        }
                        BottomToolPop.ClickType.SHARE -> {
                            share(
                                activity, content = """${article.title}
                                |${article.link}
                            """.trimMargin()
                            )
                        }
                        BottomToolPop.ClickType.EXPLORER -> {
                            activity.startActivity(Intent().apply {
                                action = Intent.ACTION_VIEW
                                data = Uri.parse(article.link)
                            })
                        }
                        BottomToolPop.ClickType.COPY -> {
                            context?.copyTextIntoClipboard(article.link, article.title)
                            showToast(R.string.copy_success)
                        }
                        BottomToolPop.ClickType.REFRESH -> {
                            refreshPage()
                        }
                    }
                }

            }))
        pop.show()
    }
    fun changeCollect() {
        if (article.collect) {
            mViewModel.uncollect(article.id)
        } else {
            mViewModel.collect(article.id)
        }
    }
    fun share(
        activity: Activity,
        title: String? = activity.getString(R.string.app_name),
        content: String?
    ) {
        ShareCompat.IntentBuilder.from(activity)
            .setType("text/plain")
            .setSubject(title)
            .setText(content)
            .setChooserTitle(title)
            .startChooser()
    }

    private fun initWeb() {
        agentWeb = AgentWeb.with(this)
            .setAgentWebParent(mViewBinding.webContainer, ViewGroup.LayoutParams(-1, -1))
            .useDefaultIndicator(getColor(R.color.textColorPrimary), 2)
            .interceptUnkownUrl()
            .setMainFrameErrorView(R.layout.include_reload, R.id.btnReload)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
            .setWebChromeClient(webChromeClient)
            .setWebViewClient(webViewClient)
            .createAgentWeb()
            .ready()
            .get()
        agentWeb?.webCreator?.webView?.run {
            overScrollMode = WebView.OVER_SCROLL_NEVER
            settings.run {
                javaScriptCanOpenWindowsAutomatically = false
                loadsImagesAutomatically = true
                useWideViewPort = true
                loadWithOverviewMode = true
                textZoom = 100
            }
        }
        agentWeb?.urlLoader?.loadUrl(article.link)
    }
    fun refreshPage() {
        agentWeb?.urlLoader?.reload()
    }

    /**
     * 进行观察订阅
     */
    override fun observeViewModel() {

    }

    private val webChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
            return super.onConsoleMessage(consoleMessage)
        }
    }

    private val webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return !whiteHostList().contains(request?.url?.host)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            view?.loadUrl(customJs(url))
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (agentWeb?.handleKeyEvent(keyCode, event) == true) {
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    override fun onPause() {
        agentWeb?.webLifeCycle?.onPause()
        super.onPause()

    }

    override fun onResume() {
        agentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        agentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    /**
     * 加载js，去掉掘金、简书、CSDN等H5页面的Title、底部操作栏，以及部分广告
     */
    private fun customJs(url: String? = article.link): String {
        val js = StringBuilder()
        js.append("javascript:(function(){")
        when (Uri.parse(url).host) {
            "juejin.im", "juejin.cn" -> {
                js.append("var followButtonList = document.getElementsByClassName('follow-button');")
                js.append("if(followButtonList&&followButtonList.length){followButtonList[0].parentNode.removeChild(followButtonList[0])}")
                js.append("var articleBannerList = document.getElementsByClassName('article-banner');")
                js.append("if(articleBannerList&&articleBannerList.length){articleBannerList[0].parentNode.removeChild(articleBannerList[0])}")
                js.append("var subscribeBtnList = document.getElementsByClassName('subscribe-btn');")
                js.append("if(subscribeBtnList&&subscribeBtnList.length){subscribeBtnList[0].parentNode.removeChild(subscribeBtnList[0])}")
                js.append("var headerList = document.getElementsByClassName('main-header-box');")
                js.append("if(headerList&&headerList.length){headerList[0].parentNode.removeChild(headerList[0])}")
                js.append("var openAppList = document.getElementsByClassName('open-in-app');")
                js.append("if(openAppList&&openAppList.length){openAppList[0].parentNode.removeChild(openAppList[0])}")
                js.append("var actionBox = document.getElementsByClassName('action-box');")
                js.append("if(actionBox&&actionBox.length){actionBox[0].parentNode.removeChild(actionBox[0])}")
                js.append("var actionBarList = document.getElementsByClassName('action-bar');")
                js.append("if(actionBarList&&actionBarList.length){actionBarList[0].parentNode.removeChild(actionBarList[0])}")
                js.append("var columnViewList = document.getElementsByClassName('column-view');")
                js.append("if(columnViewList&&columnViewList.length){columnViewList[0].style.margin = '0px'}")
            }
            "www.jianshu.com" -> {
                js.append("var badgeItemList = document.getElementsByClassName('badge-item');")
                js.append("if(badgeItemList&&badgeItemList.length){badgeItemList[0].parentNode.removeChild(badgeItemList[0])}")
                js.append("var appOpenList = document.getElementsByClassName('app-open');")
                js.append("if(appOpenList&&appOpenList.length){appOpenList[0].parentNode.removeChild(appOpenList[0])}")
                js.append("var jianshuHeader = document.getElementById('jianshu-header');")
                js.append("if(jianshuHeader){jianshuHeader.parentNode.removeChild(jianshuHeader)}")
                js.append("var commentMain = document.getElementById('comment-main');")
                js.append("if(commentMain){commentMain.parentNode.removeChild(commentMain)}")
                js.append("var footer = document.getElementById('footer');")
                js.append("if(footer){footer.parentNode.removeChild(footer)}")
                js.append("var revealAd = document.getElementById('reveal-ad');")
                js.append("if(revealAd){revealAd.parentNode.removeChild(revealAd)}")
                js.append("var headerShimList = document.getElementsByClassName('header-shim');")
                js.append("if(headerShimList&&headerShimList.length){headerShimList[0].parentNode.removeChild(headerShimList[0])}")
                js.append("var fubiaoList = document.getElementsByClassName('fubiao-dialog');")
                js.append("if(fubiaoList&&fubiaoList.length){fubiaoList[0].parentNode.removeChild(fubiaoList[0])}")
                js.append("var ads = document.getElementsByClassName('note-comment-above-ad-wrap');")
                js.append("if(ads&&ads.length){ads[0].parentNode.removeChild(ads[0])}")
                js.append("var lazyShimList = document.getElementsByClassName('v-lazy-shim');")
                js.append("if(lazyShimList&&lazyShimList.length&&lazyShimList[0]){lazyShimList[0].parentNode.removeChild(lazyShimList[0])}")
                js.append("if(lazyShimList&&lazyShimList.length&&lazyShimList[1]){lazyShimList[1].parentNode.removeChild(lazyShimList[1])}")
                js.append("var callAppBtnList = document.getElementsByClassName('call-app-btn');")
                js.append("if(callAppBtnList&&callAppBtnList.length){callAppBtnList[0].parentNode.removeChild(callAppBtnList[0])}")
            }
            "blog.csdn.net" -> {
                js.append("var detailFollow = document.getElementById('detailFollow');")
                js.append("if(detailFollow){detailFollow.parentNode.removeChild(detailFollow)}")
                js.append("var csdnToolBar = document.getElementById('csdn-toolbar');")
                js.append("if(csdnToolBar){csdnToolBar.parentNode.removeChild(csdnToolBar)}")
                js.append("var csdnMain = document.getElementById('main');")
                js.append("if(csdnMain){csdnMain.style.margin='0px'}")
                js.append("var operate = document.getElementById('operate');")
                js.append("if(operate){operate.parentNode.removeChild(operate)}")
                js.append("var haveHeartCountList = document.getElementsByClassName('have-heart-count');")
                js.append("if(haveHeartCountList&&haveHeartCountList.length){haveHeartCountList[0].parentNode.removeChild(haveHeartCountList[0])}")
                js.append("var asideHeaderFixedList = document.getElementsByClassName('aside-header-fixed');")
                js.append("if(asideHeaderFixedList&&asideHeaderFixedList.length){asideHeaderFixedList[0].parentNode.removeChild(asideHeaderFixedList[0])}")
                js.append("var feedSignSpanList = document.getElementsByClassName('feed-Sign-span');")
                js.append("if(feedSignSpanList&&feedSignSpanList.length){feedSignSpanList[0].parentNode.removeChild(feedSignSpanList[0])}")
            }
        }
        js.append("})()")
        return js.toString()
    }
}